<template>
  <div class="api-automation-page">
    <el-tabs v-model="activeTab" class="main-tabs compact-tabs">
      <!-- 环境配置 -->
      <el-tab-pane label="环境配置" name="environments">
        <div class="split-layout">
          <!-- 左侧：环境列表 -->
          <div class="left-panel">
            <div class="panel-header">
              <div class="search-filters">
                <span class="filter-label">环境管理</span>
    </div>

              <el-button type="primary" size="small" @click="showCreateEnvironmentForm">
                <el-icon><Plus /></el-icon>
                新建
              </el-button>
            </div>

            <div class="environment-list">
              <div 
                v-for="environment in environments" 
                :key="environment.id"
                class="environment-item"
                :class="{ active: selectedEnvironment?.id === environment.id }"
                @click="selectEnvironment(environment)"
              >
                <div class="environment-header">
                  <span class="environment-name">{{ environment.name }}</span>
                  <div class="environment-tags">
                    <el-tag v-if="environment.is_default" type="success" size="small">默认</el-tag>
                    <el-tag :type="environment.is_active ? 'success' : 'danger'" size="small">
                      {{ environment.is_active ? '激活' : '禁用' }}
                    </el-tag>
                  </div>
                </div>
                <div class="environment-url">{{ environment.base_url }}</div>
                <div class="environment-desc">{{ environment.description || '无描述' }}</div>
                <div class="environment-meta">
                  <span class="created-time">{{ formatDate(environment.created_at) }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧：环境详情/编辑/新建 -->
          <div class="right-panel">
            <!-- 新建环境表单 -->
            <div v-if="showCreateEnvironment" class="create-form">
              <div class="form-header">
                <h3>新建环境</h3>
                <el-button size="small" @click="cancelCreateEnvironment">
                  <el-icon><Close /></el-icon>
                  取消
                </el-button>
              </div>
              <div class="form-content">
                <el-form :model="newEnvironment" label-width="100px" size="small">
                  <el-form-item label="环境名称" required>
                    <el-input v-model="newEnvironment.name" placeholder="请输入环境名称" />
                  </el-form-item>
                  <el-form-item label="基础URL" required>
                    <el-input v-model="newEnvironment.base_url" placeholder="https://api.example.com" />
                  </el-form-item>
                  <el-form-item label="描述">
                    <el-input v-model="newEnvironment.description" type="textarea" placeholder="环境描述" />
                  </el-form-item>
                  <el-form-item label="默认环境">
                    <el-switch v-model="newEnvironment.is_default" />
                  </el-form-item>
                  <el-form-item label="激活状态">
                    <el-switch v-model="newEnvironment.is_active" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="saveEnvironment">保存</el-button>
                    <el-button @click="cancelCreateEnvironment">取消</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
            
            <!-- 环境详情 -->
            <div v-else-if="selectedEnvironment" class="environment-detail">
              <div class="detail-header">
                <div class="environment-title">
                  <span class="name">{{ selectedEnvironment.name }}</span>
                  <div class="environment-tags">
                    <el-tag v-if="selectedEnvironment.is_default" type="success" size="small">默认</el-tag>
                    <el-tag :type="selectedEnvironment.is_active ? 'success' : 'danger'" size="small">
                      {{ selectedEnvironment.is_active ? '激活' : '禁用' }}
                    </el-tag>
                  </div>
                </div>
                <div class="actions">
                  <el-button size="small" type="primary" @click="editEnvironment(selectedEnvironment)">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button size="small" type="danger" @click="deleteEnvironment(selectedEnvironment)">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </div>
              </div>

              <div class="detail-content">
                <div class="detail-section">
                  <h4>基本信息</h4>
                  <div class="info-grid">
                    <div class="info-item">
                      <label>环境名称:</label>
                      <span>{{ selectedEnvironment.name }}</span>
                    </div>
                    <div class="info-item">
                      <label>基础URL:</label>
                      <span>{{ selectedEnvironment.base_url }}</span>
                    </div>
                    <div class="info-item" v-if="selectedEnvironment.description">
                      <label>描述:</label>
                      <span>{{ selectedEnvironment.description }}</span>
                    </div>
                    <div class="info-item">
                      <label>创建时间:</label>
                      <span>{{ formatDate(selectedEnvironment.created_at) }}</span>
                    </div>
                  </div>
                </div>

                <div class="detail-section" v-if="selectedEnvironment.headers && Object.keys(selectedEnvironment.headers).length">
                  <h4>请求头配置</h4>
                  <div class="headers-list">
                    <div v-for="(value, key) in selectedEnvironment.headers" :key="key" class="header-item">
                      <span class="header-name">{{ key }}:</span>
                      <span class="header-value">{{ value }}</span>
                    </div>
                  </div>
                </div>

                <div class="detail-section" v-if="selectedEnvironment.variables && Object.keys(selectedEnvironment.variables).length">
                  <h4>环境变量</h4>
                  <div class="variables-list">
                    <div v-for="(value, key) in selectedEnvironment.variables" :key="key" class="variable-item">
                      <span class="variable-name">{{ key }}:</span>
                      <span class="variable-value">{{ value }}</span>
                    </div>
                  </div>
                </div>

                <div class="detail-section">
                  <h4>配置状态</h4>
                  <div class="status-grid">
                    <div class="status-item">
                      <label>默认环境:</label>
                      <span :class="{ 'status-yes': selectedEnvironment.is_default, 'status-no': !selectedEnvironment.is_default }">
                        {{ selectedEnvironment.is_default ? '是' : '否' }}
                      </span>
                    </div>
                    <div class="status-item">
                      <label>激活状态:</label>
                      <span :class="{ 'status-yes': selectedEnvironment.is_active, 'status-no': !selectedEnvironment.is_active }">
                        {{ selectedEnvironment.is_active ? '激活' : '禁用' }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 空状态 -->
            <div v-else class="empty-state">
              <el-empty description="请选择一个环境查看详情或点击新建按钮创建环境" />
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- 接口管理 -->
      <el-tab-pane label="接口管理" name="interfaces">
        <div class="unified-interface-layout">
          <!-- 左侧：接口列表 -->
          <div class="interface-sidebar">
                                    <div class="sidebar-header">
              <div class="search-filters">
                <el-input
                  v-model="interfaceFilters.search"
                  placeholder="搜索接口..."
                  size="small"
                  style="width: 160px"
                  @input="loadInterfaces"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
          </template>
                </el-input>
                
                <el-select
                  v-model="interfaceFilters.method"
                  placeholder="方法"
                  clearable
                  size="small"
                  style="width: 80px"
                  @change="loadInterfaces"
                >
                  <el-option label="GET" value="GET" />
                  <el-option label="POST" value="POST" />
                  <el-option label="PUT" value="PUT" />
                  <el-option label="DELETE" value="DELETE" />
                </el-select>
          </div>

              <div class="header-actions">
                <el-button type="primary" size="small" @click="createNewInterface">
                  <el-icon><Plus /></el-icon>
                  新建
                </el-button>
  </div>
            </div>

            <div class="interface-list">
              <div 
                v-for="apiInterface in interfaces" 
                :key="apiInterface.id"
                class="interface-item"
                :class="{ active: selectedInterface?.id === apiInterface.id }"
                @click="selectInterface(apiInterface)"
              >
                <div class="interface-header">
                  <el-tag :type="getMethodTagType(apiInterface.method)" size="small">
                    {{ apiInterface.method }}
                  </el-tag>
                  <span class="interface-name">{{ apiInterface.name }}</span>
                  <el-tag v-if="apiInterface.status !== 'active'" :type="getStatusTagType(apiInterface.status)" size="small">
                    {{ getStatusText(apiInterface.status) }}
                  </el-tag>
                </div>
                <div class="interface-url">{{ apiInterface.url }}</div>
                <div class="interface-meta">
                  <span v-if="apiInterface.category" class="category">{{ apiInterface.category }}</span>
                  <span class="created-time">{{ formatDate(apiInterface.created_at) }}</span>
                </div>
              </div>
            </div>

            <div class="pagination-small">
              <el-pagination
                v-model:current-page="interfacePagination.page"
                v-model:page-size="interfacePagination.size"
                :page-sizes="[10, 20, 50]"
                :total="interfacePagination.total"
                layout="prev, pager, next"
                size="small"
                @size-change="loadInterfaces"
                @current-change="loadInterfaces"
              />
            </div>
          </div>

          <!-- 右侧：统一编辑器 -->
          <div class="interface-editor">
            <!-- 新建模式 -->
            <UnifiedInterfaceEditor
              v-if="interfaceEditorMode === 'create'"
              :environments="environments"
              mode="create"
              @interface-created="handleInterfaceCreated"
              @cancel="handleEditorCancel"
            />
            
            <!-- 查看/编辑模式 -->
            <UnifiedInterfaceEditor
              v-else-if="selectedInterface && interfaceEditorMode"
              :interface-data="selectedInterface"
              :environments="environments"
              :mode="interfaceEditorMode"
              @interface-saved="handleInterfaceSaved"
              @cancel="handleEditorCancel"
            />
            
            <!-- 空状态 -->
            <div v-else class="empty-state">
              <el-empty description="请选择一个接口查看详情或点击新建按钮创建接口" />
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- 测试场景 -->
      <el-tab-pane label="测试场景" name="scenarios">
        <div class="split-layout">
          <!-- 左侧：场景列表 -->
          <div class="left-panel">
            <div class="panel-header">
              <div class="search-filters">
                <el-input
                  v-model="scenarioFilters.search"
                  placeholder="搜索场景..."
                  size="small"
                  style="width: 200px"
                  @input="loadScenarios"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
          </template>
                </el-input>
                
                <el-select
                  v-model="scenarioFilters.status"
                  placeholder="状态"
                  clearable
                  size="small"
                  style="width: 80px; margin-left: 8px"
                  @change="loadScenarios"
                >
                  <el-option label="草稿" value="draft" />
                  <el-option label="就绪" value="ready" />
                  <el-option label="运行中" value="running" />
                  <el-option label="已完成" value="completed" />
                  <el-option label="失败" value="failed" />
                </el-select>
          </div>

              <el-button type="primary" size="small" @click="showCreateScenarioForm">
                <el-icon><Plus /></el-icon>
                新建
              </el-button>
            </div>

            <div class="scenario-list">
              <div 
                v-for="scenario in scenarios" 
                :key="scenario.id"
                class="scenario-item"
                :class="{ active: selectedScenario?.id === scenario.id }"
                @click="selectScenario(scenario)"
              >
                <div class="scenario-header">
                  <span class="scenario-name">{{ scenario.name }}</span>
                  <el-tag :type="getScenarioStatusTagType(scenario.status)" size="small">
                    {{ getScenarioStatusText(scenario.status) }}
                  </el-tag>
                </div>
                <div class="scenario-desc">{{ scenario.description || '无描述' }}</div>
                <div class="scenario-meta">
                  <span class="steps-count">{{ scenario.steps ? scenario.steps.length : 0 }} 个步骤</span>
                  <span class="created-time">{{ formatDate(scenario.created_at) }}</span>
                </div>
              </div>
            </div>

            <div class="pagination-small">
              <el-pagination
                v-model:current-page="scenarioPagination.page"
                v-model:page-size="scenarioPagination.size"
                :page-sizes="[10, 20, 50]"
                :total="scenarioPagination.total"
                layout="prev, pager, next"
                size="small"
                @size-change="loadScenarios"
                @current-change="loadScenarios"
              />
            </div>
          </div>

          <!-- 右侧：场景详情/编辑/新建 -->
          <div class="right-panel">
            <!-- 新建场景表单 -->
            <div v-if="showCreateScenario" class="create-form">
              <div class="form-header">
                <h3>新建测试场景</h3>
                <el-button size="small" @click="cancelCreateScenario">
                  <el-icon><Close /></el-icon>
                  取消
                </el-button>
              </div>
              <div class="form-content">
                <el-form :model="newScenario" label-width="100px" size="small">
                  <el-form-item label="场景名称" required>
                    <el-input v-model="newScenario.name" placeholder="请输入场景名称" />
                  </el-form-item>
                  <el-form-item label="描述">
                    <el-input v-model="newScenario.description" type="textarea" placeholder="场景描述" />
                  </el-form-item>
                  <el-form-item label="执行环境">
                    <el-select v-model="newScenario.environment_id" placeholder="选择执行环境" style="width: 100%">
                      <el-option 
                        v-for="env in environments" 
                        :key="env.id" 
                        :label="env.name" 
                        :value="env.id" 
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="状态">
                    <el-select v-model="newScenario.status" placeholder="选择状态" style="width: 100%">
                      <el-option label="草稿" value="draft" />
                      <el-option label="就绪" value="ready" />
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="saveScenario">保存</el-button>
                    <el-button @click="cancelCreateScenario">取消</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
            
            <!-- 场景流程图编辑器 -->
            <div v-else-if="selectedScenario" class="scenario-flow-editor">
              <div class="flow-header">
                <div class="scenario-title">
                  <span class="name">{{ selectedScenario.name }}</span>
                  <el-tag :type="getScenarioStatusTagType(selectedScenario.status)" size="small">
                    {{ getScenarioStatusText(selectedScenario.status) }}
                  </el-tag>
                </div>
                <div class="actions">
                  <el-button size="small" type="warning" @click="debugScenario(selectedScenario)">
                    <el-icon><Tools /></el-icon>
                    调试
                  </el-button>
                  <el-button size="small" type="success" @click="executeScenario(selectedScenario)">
                    <el-icon><VideoPlay /></el-icon>
                    执行
                  </el-button>
                  <el-button size="small" type="primary" @click="editScenarioBasicInfo(selectedScenario)">
                    <el-icon><Setting /></el-icon>
                    基础设置
                  </el-button>
                  <el-button size="small" type="danger" @click="deleteScenario(selectedScenario)">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </div>
              </div>

              <!-- 流程图编辑器 -->
              <div class="flow-editor-container">
                <FlowEditor
                  ref="flowEditorRef"
                  :scenario-id="selectedScenario.id"
                  :interfaces="interfaces"
                  @save="handleFlowSave"
                  @load="handleFlowLoad"
                />
              </div>
            </div>
            
            <!-- 空状态 -->
            <div v-else class="empty-state">
              <el-empty description="请选择一个测试场景查看详情或点击新建按钮创建场景" />
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- 执行记录 -->
      <el-tab-pane label="执行记录" name="executions">
        <div class="split-layout">
          <!-- 左侧：执行记录列表 -->
          <div class="left-panel">
            <div class="panel-header">
              <div class="search-filters">
                <el-select
                  v-model="executionFilters.status"
                  placeholder="状态"
                  clearable
                  size="small"
                  style="width: 80px"
                  @change="loadExecutions"
                >
                  <el-option label="等待中" value="pending" />
                  <el-option label="运行中" value="running" />
                  <el-option label="已完成" value="completed" />
                  <el-option label="失败" value="failed" />
                  <el-option label="已取消" value="cancelled" />
                </el-select>
                
                <el-date-picker
                  v-model="executionDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始"
                  end-placeholder="结束"
                  size="small"
                  style="width: 200px; margin-left: 8px"
                  @change="loadExecutions"
                />
              </div>
              
              <el-button size="small" @click="loadExecutions">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>

            <div class="execution-list">
              <div 
                v-for="execution in executions" 
                :key="execution.id"
                class="execution-item"
                :class="{ active: selectedExecution?.id === execution.id }"
                @click="selectExecution(execution)"
              >
                <div class="execution-header">
                  <span class="execution-id">{{ execution.execution_id }}</span>
                  <el-tag :type="getExecutionStatusTagType(execution.status)" size="small">
                    {{ getExecutionStatusText(execution.status) }}
                  </el-tag>
                </div>
                <div class="execution-scenario">{{ execution.scenario ? execution.scenario.name : '未知场景' }}</div>
                <div class="execution-meta">
                  <div class="execution-results">
                    <span class="passed">✓ {{ execution.passed_steps }}</span>
                    <span class="failed">✗ {{ execution.failed_steps }}</span>
                    <span class="skipped">⊘ {{ execution.skipped_steps }}</span>
                  </div>
                  <div class="execution-time">
                    <span class="duration">{{ execution.duration ? `${execution.duration.toFixed(2)}s` : '-' }}</span>
                    <span class="created-time">{{ formatDate(execution.created_at) }}</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="pagination-small">
              <el-pagination
                v-model:current-page="executionPagination.page"
                v-model:page-size="executionPagination.size"
                :page-sizes="[10, 20, 50]"
                :total="executionPagination.total"
                layout="prev, pager, next"
                size="small"
                @size-change="loadExecutions"
                @current-change="loadExecutions"
              />
            </div>
          </div>

          <!-- 右侧：执行详情 -->
          <div class="right-panel">
            <div v-if="!selectedExecution" class="empty-state">
              <el-empty description="请选择一个执行记录查看详情" />
            </div>
            
            <div v-else class="execution-detail">
              <div class="detail-header">
                <div class="execution-title">
                  <span class="name">{{ selectedExecution.execution_id }}</span>
                  <el-tag :type="getExecutionStatusTagType(selectedExecution.status)" size="small">
                    {{ getExecutionStatusText(selectedExecution.status) }}
                  </el-tag>
                </div>
                <div class="actions">
                  <el-button size="small" type="info" @click="viewExecutionDetail(selectedExecution)">
                    <el-icon><View /></el-icon>
                    详细报告
                  </el-button>
                </div>
              </div>

              <div class="detail-content">
                <div class="detail-section">
                  <h4>执行概要</h4>
                  <div class="info-grid">
                    <div class="info-item">
                      <label>场景:</label>
                      <span>{{ selectedExecution.scenario ? selectedExecution.scenario.name : '未知场景' }}</span>
                    </div>
                    <div class="info-item">
                      <label>执行时间:</label>
                      <span>{{ formatDate(selectedExecution.created_at) }}</span>
                    </div>
                    <div class="info-item">
                      <label>耗时:</label>
                      <span>{{ selectedExecution.duration ? `${selectedExecution.duration.toFixed(2)}s` : '-' }}</span>
                    </div>
                  </div>
                </div>

                <div class="detail-section">
                  <h4>执行结果</h4>
                  <div class="result-summary">
                    <div class="result-item passed">
                      <span class="label">通过</span>
                      <span class="count">{{ selectedExecution.passed_steps }}</span>
                    </div>
                    <div class="result-item failed">
                      <span class="label">失败</span>
                      <span class="count">{{ selectedExecution.failed_steps }}</span>
                    </div>
                    <div class="result-item skipped">
                      <span class="label">跳过</span>
                      <span class="count">{{ selectedExecution.skipped_steps }}</span>
                    </div>
                  </div>
                </div>

                <div class="detail-section" v-if="selectedExecution.error_message">
                  <h4>错误信息</h4>
                  <div class="error-message">
                    {{ selectedExecution.error_message }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>


    </el-tabs>

    <!-- 接口创建/编辑对话框已删除，使用统一编辑器替代 -->

    <!-- 场景创建/编辑对话框 -->
    <ScenarioDialog
      v-model:visible="scenarioDialogVisible"
      :scenario-data="currentScenario"
      :is-edit="isEditScenario"
      @confirm="handleScenarioSubmit"
    />

    <!-- 场景编辑抽屉 -->
    <el-drawer
      v-model="scenarioDrawerVisible"
      title="编辑测试场景"
      direction="rtl"
      size="60%"
      :before-close="handleDrawerClose"
    >
      <div v-if="editingScenario" class="drawer-content">
        <el-form :model="editingScenario" label-width="100px" size="default">
          <el-form-item label="场景名称" required>
            <el-input v-model="editingScenario.name" placeholder="请输入场景名称" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="editingScenario.description" type="textarea" :rows="3" placeholder="场景描述" />
          </el-form-item>
          <el-form-item label="执行环境">
            <el-select v-model="editingScenario.environment_id" placeholder="选择执行环境" style="width: 100%">
              <el-option 
                v-for="env in environments" 
                :key="env.id" 
                :label="env.name" 
                :value="env.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="editingScenario.status" placeholder="选择状态" style="width: 100%">
              <el-option label="草稿" value="draft" />
              <el-option label="就绪" value="ready" />
              <el-option label="运行中" value="running" />
              <el-option label="已完成" value="completed" />
              <el-option label="失败" value="failed" />
            </el-select>
          </el-form-item>
          
          <!-- 场景步骤 -->
          <el-form-item label="测试步骤">
            <div class="steps-section">
              <div class="steps-header">
                <span>场景包含 {{ editingScenario.steps ? editingScenario.steps.length : 0 }} 个步骤</span>
                <el-button type="primary" size="small" @click="addScenarioStep">
                  <el-icon><Plus /></el-icon>
                  添加步骤
                </el-button>
              </div>
              
              <div v-if="!editingScenario.steps || editingScenario.steps.length === 0" class="empty-steps">
                <el-empty description="暂无测试步骤，点击添加步骤开始配置" />
              </div>
              
              <div v-else class="steps-list">
                <div 
                  v-for="(step, index) in editingScenario.steps" 
                  :key="index" 
                  class="step-item"
                >
                  <div class="step-header">
                    <span class="step-number">步骤 {{ index + 1 }}</span>
                    <div class="step-actions">
                      <el-button size="small" @click="editScenarioStep(step, index)">
                        <el-icon><Edit /></el-icon>
                        编辑
                      </el-button>
                      <el-button size="small" type="danger" @click="removeScenarioStep(index)">
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-button>
                    </div>
                  </div>
                  
                  <div v-if="step.selectedInterface" class="step-interface">
                    <el-tag :type="getMethodTagType(step.selectedInterface.method)" size="small">
                      {{ step.selectedInterface.method }}
                    </el-tag>
                    <span class="interface-name">{{ step.selectedInterface.name }}</span>
                    <span class="interface-url">{{ step.selectedInterface.url }}</span>
                  </div>
                  
                  <div v-if="step.parameter_overrides && step.parameter_overrides.length > 0" class="step-params">
                    <span class="params-label">参数覆盖:</span>
                    <el-tag v-for="override in step.parameter_overrides" :key="override.name" size="small" style="margin-left: 4px">
                      {{ override.name }}: {{ override.value }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveScenarioChanges" :loading="savingScenario">
              保存更改
            </el-button>
            <el-button @click="cancelScenarioEdit">
              取消
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

    <!-- 环境配置创建/编辑对话框 -->
    <EnvironmentDialog
      v-model:visible="environmentDialogVisible"
      :environment-data="currentEnvironment"
      :is-edit="isEditEnvironment"
      @confirm="handleEnvironmentSubmit"
    />

    <!-- 接口测试对话框已删除，使用统一编辑器替代 -->

    <!-- 执行详情对话框 -->
    <ExecutionDetailDialog
      v-model:visible="executionDetailVisible"
      :execution-data="currentExecution"
    />

    <!-- 场景步骤编辑对话框已废弃，使用流程图编辑器替代 -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useToast } from 'vue-toastification'
import { ElMessageBox } from 'element-plus'
import { Tools, Close, Check, Plus, Delete, QuestionFilled, Setting } from '@element-plus/icons-vue'
import { apiAutomationApi } from '@/api/apiAutomation'

// 导入子组件
import ScenarioDialog from './components/ScenarioDialog.vue'
import EnvironmentDialog from './components/EnvironmentDialog.vue'
// InterfaceTestDialog已删除，使用统一编辑器替代
import ExecutionDetailDialog from './components/ExecutionDetailDialog.vue'
import FlowEditor from '@/components/FlowEditor.vue'
import UnifiedInterfaceEditor from './components/UnifiedInterfaceEditor.vue'
// InterfaceDialog已删除，使用统一编辑器替代
// ScenarioStepDialog已废弃，使用流程图编辑器替代

const toast = useToast()

// 当前激活的标签页
const activeTab = ref('environments')

// ==================== 接口管理 ====================
const interfaces = ref([])
const interfaceLoading = ref(false)
const selectedInterface = ref(null)
const interfaceFilters = reactive({
  search: '',
  method: '',
  status: '',
  category: ''
})
const interfacePagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 旧的内联表单相关变量已删除，使用统一编辑器替代

// 统一接口编辑器相关
const interfaceEditorMode = ref('view') // view, edit, create

// 旧的接口对话框相关变量已删除，使用统一编辑器替代

// 旧的接口测试相关变量已删除，使用统一编辑器替代

// ==================== 测试场景 ====================
const scenarios = ref([])
const scenarioLoading = ref(false)
const selectedScenario = ref(null)
const scenarioFilters = reactive({
  search: '',
  status: ''
})
const scenarioPagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 场景内联表单相关
const showCreateScenario = ref(false)
const newScenario = reactive({
  name: '',
  description: '',
  environment_id: null,
  status: 'draft',
  steps: []
})

// 场景对话框相关（保留兼容性）
const scenarioDialogVisible = ref(false)
const currentScenario = ref(null)
const isEditScenario = ref(false)

// 场景编辑抽屉相关
const scenarioDrawerVisible = ref(false)
const editingScenario = ref(null)
const savingScenario = ref(false)

// 步骤编辑相关 - 已废弃，使用流程图编辑器替代

// 流程图编辑器相关
const flowEditorRef = ref(null)

// 处理流程图保存
const handleFlowSave = async (flowData) => {
  if (!selectedScenario.value) return
  
  try {
    // 调用后端API保存流程图数据
    await apiAutomationApi.saveScenarioFlow(selectedScenario.value.id, flowData)
    toast.success('流程图保存成功')
  } catch (error) {
    console.error('保存流程图失败:', error)
    toast.error('保存流程图失败')
  }
}

// 处理流程图加载
const handleFlowLoad = async () => {
  if (!selectedScenario.value) return
  
  try {
    // 调用后端API加载流程图数据
    const response = await apiAutomationApi.getScenarioFlow(selectedScenario.value.id)
    if (response && response.data && flowEditorRef.value) {
      flowEditorRef.value.loadFlowData(response.data)
    }
  } catch (error) {
    console.error('加载流程图失败:', error)
    // 如果没有流程图数据，这是正常的，不需要显示错误
  }
}

// ==================== 执行记录 ====================
const executions = ref([])
const executionLoading = ref(false)
const selectedExecution = ref(null)
const executionFilters = reactive({
  status: ''
})
const executionDateRange = ref([])
const executionPagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 执行详情相关
const executionDetailVisible = ref(false)
const currentExecution = ref(null)

// ==================== 环境配置 ====================
const environments = ref([])
const environmentLoading = ref(false)
const selectedEnvironment = ref(null)

// 环境配置内联表单相关
const showCreateEnvironment = ref(false)
const newEnvironment = reactive({
  name: '',
  base_url: '',
  description: '',
  is_default: false,
  is_active: true,
  headers: {},
  variables: {}
})

// 环境配置对话框相关（保留兼容性）
const environmentDialogVisible = ref(false)
const currentEnvironment = ref(null)
const isEditEnvironment = ref(false)

// ==================== 方法定义 ====================

// 加载接口列表
const loadInterfaces = async () => {
  interfaceLoading.value = true
  try {
    const params = {
      page: interfacePagination.page,
      size: interfacePagination.size,
      ...interfaceFilters
    }
    const response = await apiAutomationApi.getInterfaces(params)
    if (response && response.data) {
      interfaces.value = Array.isArray(response.data.items) ? response.data.items : []
      interfacePagination.total = response.data.total || 0
    } else {
      interfaces.value = []
      interfacePagination.total = 0
    }
  } catch (error) {
    toast.error('加载接口列表失败')
    interfaces.value = []
    interfacePagination.total = 0
  } finally {
    interfaceLoading.value = false
  }
}

// 旧的选择接口方法已移动到统一编辑器部分

// 旧的内联表单相关方法已删除，使用统一编辑器替代

// 旧的对话框编辑方法已删除，使用统一编辑器替代

// 旧的测试接口方法已删除，使用统一编辑器替代

// 统一编辑器相关方法
const createNewInterface = () => {
  interfaceEditorMode.value = 'create'
  selectedInterface.value = null
}

const selectInterface = (interfaceData) => {
  selectedInterface.value = interfaceData
  interfaceEditorMode.value = 'view'
}

const handleInterfaceCreated = async (newInterface) => {
  // 重新加载接口列表
  await loadInterfaces()
  
  // 选中新创建的接口
  selectedInterface.value = newInterface
  interfaceEditorMode.value = 'view'
  
  toast.success('接口创建成功')
}

const handleInterfaceSaved = async (updatedInterface) => {
  // 更新接口列表中的数据
  const index = interfaces.value.findIndex(item => item.id === updatedInterface.id)
  if (index !== -1) {
    interfaces.value[index] = updatedInterface
  }
  
  // 更新当前选中的接口
  selectedInterface.value = updatedInterface
  interfaceEditorMode.value = 'view'
  
  // 旧的测试对话框更新逻辑已删除
  
  toast.success('接口保存成功')
}

const handleEditorCancel = () => {
  if (interfaceEditorMode.value === 'create') {
    interfaceEditorMode.value = 'view'
    selectedInterface.value = null
  } else {
    interfaceEditorMode.value = 'view'
  }
}

// 处理接口更新
const handleInterfaceUpdated = async (updatedInterface) => {
  // 更新接口列表中的数据
  const index = interfaces.value.findIndex(item => item.id === updatedInterface.id)
  if (index !== -1) {
    interfaces.value[index] = updatedInterface
  }
  
  // 如果当前选中的是这个接口，也要更新
  if (selectedInterface.value && selectedInterface.value.id === updatedInterface.id) {
    selectedInterface.value = updatedInterface
  }
  
  // 旧的测试对话框更新逻辑已删除
}

// 删除接口
const deleteInterface = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除接口 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await apiAutomationApi.deleteInterface(row.id)
    toast.success('删除成功')
    loadInterfaces()
  } catch (error) {
    if (error !== 'cancel') {
      toast.error('删除失败')
    }
  }
}

// 加载场景列表
const loadScenarios = async () => {
  scenarioLoading.value = true
  try {
    const params = {
      page: scenarioPagination.page,
      size: scenarioPagination.size,
      ...scenarioFilters
    }
    const response = await apiAutomationApi.getScenarios(params)
    if (response && response.data) {
      scenarios.value = Array.isArray(response.data.items) ? response.data.items : []
      scenarioPagination.total = response.data.total || 0
    } else {
      scenarios.value = []
      scenarioPagination.total = 0
    }
  } catch (error) {
    toast.error('加载场景列表失败')
    scenarios.value = []
    scenarioPagination.total = 0
  } finally {
    scenarioLoading.value = false
  }
}

// 选择场景
const selectScenario = async (scenario) => {
  selectedScenario.value = scenario
  showCreateScenario.value = false // 关闭新建表单
  
  // 延迟加载流程数据，确保FlowEditor组件已经渲染
  await nextTick()
  if (flowEditorRef.value) {
    await handleFlowLoad()
  }
}

// 显示内联创建场景表单
const showCreateScenarioForm = () => {
  showCreateScenario.value = true
  selectedScenario.value = null // 清除选中状态
  // 重置表单
  Object.assign(newScenario, {
    name: '',
    description: '',
    environment_id: null,
    status: 'draft',
    steps: []
  })
}

// 取消创建场景
const cancelCreateScenario = () => {
  showCreateScenario.value = false
}

// 保存场景
const saveScenario = async () => {
  try {
    const response = await apiAutomationApi.createScenario(newScenario)
    if (response && response.data) {
      toast.success('测试场景创建成功')
      showCreateScenario.value = false
      await loadScenarios()
      // 选中新创建的场景
      selectedScenario.value = response.data
    }
  } catch (error) {
    console.error('创建场景失败:', error)
    toast.error('创建场景失败')
  }
}

// 显示创建场景对话框（保留兼容性）
const showCreateScenarioDialog = () => {
  currentScenario.value = null
  isEditScenario.value = false
  scenarioDialogVisible.value = true
}

// 编辑场景（对话框方式，保留兼容性）
const editScenario = (row) => {
  currentScenario.value = { ...row }
  isEditScenario.value = true
  scenarioDialogVisible.value = true
}

// 编辑场景基础信息
const editScenarioBasicInfo = (scenario) => {
  currentScenario.value = { ...scenario }
  isEditScenario.value = true
  scenarioDialogVisible.value = true
}

// 在抽屉中编辑场景（保留兼容性）
const editScenarioInDrawer = (scenario) => {
  editingScenario.value = JSON.parse(JSON.stringify(scenario)) // 深拷贝
  scenarioDrawerVisible.value = true
}

// 关闭抽屉前的确认
const handleDrawerClose = (done) => {
  if (savingScenario.value) {
    return
  }
  
  ElMessageBox.confirm('确定要关闭吗？未保存的更改将丢失。', '确认关闭', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    done()
  }).catch(() => {
    // 取消关闭
  })
}

// 保存场景更改
const saveScenarioChanges = async () => {
  if (!editingScenario.value) return
  
  savingScenario.value = true
  try {
    // 过滤掉不需要的字段，但保留所有可更新的字段
    const { id, created_at, updated_at, created_by, creator, executions, steps, ...updateData } = editingScenario.value
    
    // 处理步骤数据，确保数据结构正确
    if (steps && Array.isArray(steps)) {
      updateData.steps = steps.map((step, index) => {
        // 移除前端特有的字段和数据库字段
        const { id, selectedInterface, scenario_id, interface: stepInterface, ...cleanStep } = step
        
        // 构建符合后端期望的步骤数据
        const processedStep = {
          name: cleanStep.name || `步骤 ${index + 1}`,
          description: cleanStep.description || null,
          step_order: cleanStep.step_order || (index + 1),
          step_type: cleanStep.step_type || 'api_call',
          is_enabled: cleanStep.is_enabled !== undefined ? Boolean(cleanStep.is_enabled) : true,
          continue_on_failure: cleanStep.continue_on_failure !== undefined ? Boolean(cleanStep.continue_on_failure) : false,
          parameter_overrides: cleanStep.parameter_overrides || {},
          variable_extractions: cleanStep.variable_extractions || {},
          interface_id: cleanStep.interface_id || null
        }
        
        // 确保JSON字段不为null（使用空对象）
        if (!processedStep.parameter_overrides) {
          processedStep.parameter_overrides = {}
        }
        if (!processedStep.variable_extractions) {
          processedStep.variable_extractions = {}
        }
        
        return processedStep
      })
    }
    
    const response = await apiAutomationApi.updateScenario(editingScenario.value.id, updateData)
    if (response && response.data) {
      toast.success('场景更新成功')
      scenarioDrawerVisible.value = false
      // 重新加载场景列表
      await loadScenarios()
      // 强制更新选中的场景
      selectedScenario.value = response.data
      // 确保界面重新渲染
      await nextTick()
    }
  } catch (error) {
    console.error('更新场景失败:', error)
    console.error('错误详情:', error.response?.data)
    
    let errorMessage = '更新场景失败'
    if (error.response?.data?.detail) {
      if (Array.isArray(error.response.data.detail)) {
        // Pydantic validation errors
        const validationErrors = error.response.data.detail.map(err => 
          `${err.loc?.join('.')} - ${err.msg}`
        ).join('; ')
        errorMessage += `: ${validationErrors}`
      } else {
        errorMessage += `: ${error.response.data.detail}`
      }
    } else {
      errorMessage += `: ${error.message}`
    }
    
    toast.error(errorMessage)
  } finally {
    savingScenario.value = false
  }
}

// 取消场景编辑
const cancelScenarioEdit = () => {
  scenarioDrawerVisible.value = false
}

// 旧的步骤相关方法已废弃，使用流程图编辑器替代

// 查看场景详情
const viewScenario = (row) => {
  selectScenario(row)
}

// 调试场景
const debugScenario = async (row) => {
  try {
    const response = await apiAutomationApi.debugScenarioFlow(row.id, {
      environment_id: null,
      variables: {}
    })
    toast.success(`场景调试已启动，执行ID: ${response.data.execution_id}`)
    // 切换到执行记录标签页
    activeTab.value = 'executions'
    loadExecutions()
  } catch (error) {
    console.error('场景调试失败:', error)
    toast.error('场景调试失败')
  }
}

// 执行场景
const executeScenario = async (row) => {
  try {
    const response = await apiAutomationApi.executeScenarioFlow(row.id, {
      environment_id: null,
      variables: {}
    })
    toast.success(`场景执行已启动，执行ID: ${response.data.execution_id}`)
    // 切换到执行记录标签页
    activeTab.value = 'executions'
    loadExecutions()
  } catch (error) {
    console.error('场景执行失败:', error)
    toast.error('场景执行失败')
  }
}

// 删除场景
const deleteScenario = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除场景 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await apiAutomationApi.deleteScenario(row.id)
    toast.success('删除成功')
    loadScenarios()
  } catch (error) {
    if (error !== 'cancel') {
      toast.error('删除失败')
    }
  }
}

// 处理场景提交
const handleScenarioSubmit = (scenarioData) => {
  scenarioDialogVisible.value = false
  loadScenarios()
  // 如果是编辑模式，更新选中的场景
  if (isEditScenario.value && scenarioData) {
    selectedScenario.value = scenarioData
  }
}

// 加载执行记录列表
const loadExecutions = async () => {
  executionLoading.value = true
  try {
    const params = {
      page: executionPagination.page,
      size: executionPagination.size,
      ...executionFilters
    }
    
    if (executionDateRange.value && executionDateRange.value.length === 2) {
      params.start_date = executionDateRange.value[0]
      params.end_date = executionDateRange.value[1]
    }
    
    const response = await apiAutomationApi.getExecutions(params)
    if (response && response.data) {
      executions.value = Array.isArray(response.data.items) ? response.data.items : []
      executionPagination.total = response.data.total || 0
    } else {
      executions.value = []
      executionPagination.total = 0
    }
  } catch (error) {
    toast.error('加载执行记录失败')
    executions.value = []
    executionPagination.total = 0
  } finally {
    executionLoading.value = false
  }
}

// 选择执行记录
const selectExecution = (execution) => {
  selectedExecution.value = execution
}

// 查看执行记录
const viewExecution = (row) => {
  selectExecution(row)
}

// 查看执行详情
const viewExecutionDetail = (row) => {
  currentExecution.value = row
  executionDetailVisible.value = true
}

// 加载环境配置列表
const loadEnvironments = async () => {
  environmentLoading.value = true
  try {
    const response = await apiAutomationApi.getEnvironments()
    if (response && response.data) {
      environments.value = Array.isArray(response.data) ? response.data : []
    } else {
      environments.value = []
    }
  } catch (error) {
    toast.error('加载环境配置失败')
    environments.value = []
  } finally {
    environmentLoading.value = false
  }
}

// 选择环境
const selectEnvironment = (environment) => {
  selectedEnvironment.value = environment
  showCreateEnvironment.value = false // 关闭新建表单
}

// 显示内联创建环境表单
const showCreateEnvironmentForm = () => {
  showCreateEnvironment.value = true
  selectedEnvironment.value = null // 清除选中状态
  // 重置表单
  Object.assign(newEnvironment, {
    name: '',
    base_url: '',
    description: '',
    is_default: false,
    is_active: true,
    headers: {},
    variables: {}
  })
}

// 取消创建环境
const cancelCreateEnvironment = () => {
  showCreateEnvironment.value = false
}

// 保存环境
const saveEnvironment = async () => {
  try {
    const response = await apiAutomationApi.createEnvironment(newEnvironment)
    if (response && response.data) {
      toast.success('环境创建成功')
      showCreateEnvironment.value = false
      await loadEnvironments()
      // 选中新创建的环境
      selectedEnvironment.value = response.data
    }
  } catch (error) {
    console.error('创建环境失败:', error)
    toast.error('创建环境失败')
  }
}

// 显示创建环境对话框（保留兼容性）
const showCreateEnvironmentDialog = () => {
  currentEnvironment.value = null
  isEditEnvironment.value = false
  environmentDialogVisible.value = true
}

// 编辑环境配置
const editEnvironment = (row) => {
  currentEnvironment.value = { ...row }
  isEditEnvironment.value = true
  environmentDialogVisible.value = true
}

// 删除环境配置
const deleteEnvironment = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除环境配置 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await apiAutomationApi.deleteEnvironment(row.id)
    toast.success('删除成功')
    loadEnvironments()
  } catch (error) {
    if (error !== 'cancel') {
      toast.error('删除失败')
    }
  }
}

// 处理环境配置提交
const handleEnvironmentSubmit = () => {
  environmentDialogVisible.value = false
  loadEnvironments()
}

// ==================== 辅助方法 ====================

// 获取请求方法标签类型
const getMethodTagType = (method) => {
  const types = {
    GET: 'success',
    POST: 'primary',
    PUT: 'warning',
    DELETE: 'danger',
    PATCH: 'info'
  }
  return types[method] || 'info'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    active: 'success',
    inactive: 'warning',
    deprecated: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    active: '激活',
    inactive: '禁用',
    deprecated: '废弃'
  }
  return texts[status] || status
}

// 获取场景状态标签类型
const getScenarioStatusTagType = (status) => {
  const types = {
    draft: 'info',
    ready: 'success',
    running: 'warning',
    completed: 'success',
    failed: 'danger'
  }
  return types[status] || 'info'
}

// 获取场景状态文本
const getScenarioStatusText = (status) => {
  const texts = {
    draft: '草稿',
    ready: '就绪',
    running: '运行中',
    completed: '已完成',
    failed: '失败'
  }
  return texts[status] || status
}

// 获取执行状态标签类型
const getExecutionStatusTagType = (status) => {
  const types = {
    pending: 'info',
    running: 'warning',
    completed: 'success',
    failed: 'danger',
    cancelled: 'info'
  }
  return types[status] || 'info'
}

// 获取执行状态文本
const getExecutionStatusText = (status) => {
  const texts = {
    pending: '等待中',
    running: '运行中',
    completed: '已完成',
    failed: '失败',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// ==================== 生命周期 ====================
onMounted(() => {
  loadInterfaces()
  loadScenarios()
  loadExecutions()
  loadEnvironments()
})
</script>

<style lang="scss" scoped>
.api-automation-page {
  padding: 8px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  font-size: 13px;
  
  .compact-tabs {
    background: white;
    border-radius: 6px;
    box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.08);
    
    :deep(.el-tabs__header) {
      margin: 0;
      padding: 0 16px;
      background: #fafbfc;
      border-radius: 6px 6px 0 0;
      border-bottom: 1px solid #e4e7ed;
    }
    
    :deep(.el-tabs__nav-wrap) {
      padding: 8px 0;
    }
    
    :deep(.el-tabs__item) {
      font-size: 13px;
      padding: 0 16px;
      height: 32px;
      line-height: 32px;
    }
    
    :deep(.el-tabs__content) {
      padding: 0;
    }
  }
}

.split-layout {
  display: flex;
  height: calc(100vh - 140px);
  
  .left-panel {
    width: 400px;
    border-right: 1px solid #e4e7ed;
    display: flex;
    flex-direction: column;
    
    .panel-header {
      padding: 12px 16px;
      border-bottom: 1px solid #e4e7ed;
      background: #fafbfc;
  display: flex;
  justify-content: space-between;
  align-items: center;
      
      .search-filters {
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }
    
    .interface-list {
      flex: 1;
      overflow-y: auto;
      padding: 8px;
    }
    
    .pagination-small {
      padding: 8px 16px;
      border-top: 1px solid #e4e7ed;
      background: #fafbfc;
  text-align: center;
    }
  }
  
  .right-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #fafbfc;
    
    .empty-state {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .interface-detail {
      flex: 1;
      display: flex;
      flex-direction: column;
      
      .detail-content {
        flex: 1;
        overflow-y: auto;
        padding: 16px;
        background: white;
      }
    }
  }
}

.interface-item {
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  }
  
  &.active {
    border-color: #409eff;
    background: #f0f8ff;
  }
  
  .interface-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
    
    .interface-name {
      font-weight: 500;
      flex: 1;
      font-size: 13px;
    }
  }
  
  .interface-url {
    color: #666;
    font-size: 12px;
    margin-bottom: 6px;
    word-break: break-all;
  }
  
  .interface-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 11px;
    color: #999;
    
    .category {
      background: #f0f2f5;
      padding: 2px 6px;
      border-radius: 3px;
    }
  }
}

.detail-section {
  margin-bottom: 20px;
  
  h4 {
    margin: 0 0 12px 0;
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    border-bottom: 1px solid #e4e7ed;
    padding-bottom: 6px;
  }
}

.info-grid {
  .info-item {
    display: flex;
    margin-bottom: 8px;
    font-size: 13px;
    
    label {
      width: 80px;
    color: #666;
      font-weight: 500;
    }
    
    span {
      flex: 1;
      color: #303133;
      word-break: break-all;
    }
  }
}

.param-list {
  .param-item {
    padding: 10px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    margin-bottom: 8px;
    background: #fafbfc;
    
    .param-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 6px;
      
      .param-name {
        font-weight: 500;
        font-size: 13px;
      }
    }
    
    .param-meta {
      display: flex;
      gap: 12px;
      margin-bottom: 4px;
      font-size: 12px;
      color: #666;
      
      .param-type {
        background: #e1f3d8;
        padding: 2px 6px;
        border-radius: 3px;
      }
      
      .param-data-type {
        background: #fdf6ec;
        padding: 2px 6px;
        border-radius: 3px;
      }
    }
    
    .param-desc {
      font-size: 12px;
      color: #666;
    }
  }
}

.assertion-list {
  .assertion-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    margin-bottom: 6px;
    background: #fafbfc;
    font-size: 12px;
    
    .assertion-name {
      font-weight: 500;
    }
    
    .assertion-type {
      color: #666;
      background: #f0f2f5;
      padding: 2px 6px;
      border-radius: 3px;
    }
  }
}

/* 场景列表样式 */
.scenario-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.scenario-item {
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  }
  
  &.active {
    border-color: #409eff;
    background: #f0f8ff;
  }
  
  .scenario-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 6px;
    
    .scenario-name {
      font-weight: 500;
      font-size: 13px;
      flex: 1;
    }
  }
  
  .scenario-desc {
    color: #666;
    font-size: 12px;
    margin-bottom: 6px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  
  .scenario-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 11px;
    color: #999;
    
    .steps-count {
      background: #f0f2f5;
      padding: 2px 6px;
      border-radius: 3px;
    }
  }
}

/* 流程图编辑器样式 */
.scenario-flow-editor {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .flow-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 8px 8px 0 0;
    margin-bottom: 0;
    
    .scenario-title {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .name {
        font-size: 16px;
  font-weight: 600;
      }
    }
    
    .actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .flow-editor-container {
    flex: 1;
    height: calc(100vh - 200px);
    border: 1px solid #e4e7ed;
    border-radius: 0 0 8px 8px;
    overflow: hidden;
  }
}

.scenario-detail {
  .detail-content {
    .steps-list {
      .step-item {
        padding: 10px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        margin-bottom: 8px;
        background: #fafbfc;
        
        .step-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 6px;
          
          .step-number {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #409eff;
            color: white;
            font-size: 11px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 500;
          }
          
          .step-name {
            font-weight: 500;
            font-size: 13px;
          }
        }
        
        .step-interface {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 4px;
          font-size: 12px;
          
          .interface-url {
            color: #666;
          }
        }
        
        .step-params {
          font-size: 11px;
          color: #999;
        }
      }
    }
  }
}

/* 执行记录列表样式 */
.execution-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.execution-item {
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  }
  
  &.active {
    border-color: #409eff;
    background: #f0f8ff;
  }
  
  .execution-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 6px;
    
    .execution-id {
      font-weight: 500;
      font-size: 12px;
      font-family: monospace;
    }
  }
  
  .execution-scenario {
    color: #666;
    font-size: 12px;
    margin-bottom: 8px;
    font-weight: 500;
  }
  
  .execution-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 11px;
    
    .execution-results {
      display: flex;
      gap: 8px;
      
      .passed { color: #67C23A; }
      .failed { color: #F56C6C; }
      .skipped { color: #E6A23C; }
    }
    
    .execution-time {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      gap: 2px;
      color: #999;
      
      .duration {
        font-weight: 500;
      }
    }
  }
}

.execution-detail {
  .detail-content {
    .result-summary {
      display: flex;
      gap: 16px;
      
      .result-item {
        flex: 1;
        padding: 12px;
        border-radius: 6px;
  text-align: center;
        
        &.passed {
          background: #f0f9ff;
          border: 1px solid #67C23A;
          
          .label { color: #67C23A; }
          .count { color: #67C23A; font-weight: bold; }
        }
        
        &.failed {
          background: #fef0f0;
          border: 1px solid #F56C6C;
          
          .label { color: #F56C6C; }
          .count { color: #F56C6C; font-weight: bold; }
        }
        
        &.skipped {
          background: #fdf6ec;
          border: 1px solid #E6A23C;
          
          .label { color: #E6A23C; }
          .count { color: #E6A23C; font-weight: bold; }
        }
        
        .label {
          display: block;
          font-size: 12px;
          margin-bottom: 4px;
        }
        
        .count {
          display: block;
          font-size: 18px;
        }
      }
    }
    
    .error-message {
      padding: 12px;
      background: #fef0f0;
      border: 1px solid #F56C6C;
      border-radius: 4px;
      color: #F56C6C;
      font-size: 12px;
      font-family: monospace;
      white-space: pre-wrap;
    }
  }
}

/* 环境列表样式 */
.environment-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.environment-item {
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  }
  
  &.active {
    border-color: #409eff;
    background: #f0f8ff;
  }
  
  .environment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 6px;
    
    .environment-name {
      font-weight: 500;
      font-size: 13px;
      flex: 1;
    }
    
    .environment-tags {
      display: flex;
      gap: 4px;
    }
  }
  
  .environment-url {
    color: #666;
    font-size: 12px;
    margin-bottom: 6px;
    word-break: break-all;
    font-family: monospace;
  }
  
  .environment-desc {
    color: #999;
    font-size: 11px;
    margin-bottom: 6px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  
  .environment-meta {
    font-size: 11px;
    color: #999;
    text-align: right;
  }
}

.environment-detail {
  .detail-content {
    .environment-tags {
      display: flex;
      gap: 8px;
      align-items: center;
    }
    
    .headers-list, .variables-list {
      .header-item, .variable-item {
        display: flex;
        padding: 8px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        margin-bottom: 6px;
        background: #fafbfc;
        font-size: 12px;
        
        .header-name, .variable-name {
          font-weight: 500;
          min-width: 120px;
          color: #666;
        }
        
        .header-value, .variable-value {
          flex: 1;
    color: #303133;
          word-break: break-all;
          font-family: monospace;
        }
      }
    }
    
    .status-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16px;
      
      .status-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        background: #fafbfc;
        font-size: 13px;
        
        label {
    color: #666;
          font-weight: 500;
        }
        
        .status-yes {
          color: #67C23A;
          font-weight: 500;
        }
        
        .status-no {
          color: #999;
        }
      }
    }
  }
}

.filter-label {
  font-size: 13px;
  color: #666;
  font-weight: 500;
}

/* 右侧面板优化 */
.right-panel {
  padding: 16px;
  background: #f8f9fa;
  
  .empty-state {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  }
}

/* 内联创建表单样式 */
.create-form {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  
  .form-header {
    padding: 20px 24px 16px 24px;
    border-bottom: 1px solid #e4e7ed;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: white;
      display: flex;
      align-items: center;
      gap: 8px;
      
      &::before {
        content: "✨";
    font-size: 16px;
      }
    }
    
    .el-button {
      background: rgba(255, 255, 255, 0.2);
      border: 1px solid rgba(255, 255, 255, 0.3);
      color: white;
      
      &:hover {
        background: rgba(255, 255, 255, 0.3);
        border-color: rgba(255, 255, 255, 0.5);
      }
    }
  }
  
  .form-content {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
    background: #fafbfc;
    
    .el-form {
      background: white;
      padding: 24px;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
      max-width: none;
      
      .el-form-item {
        margin-bottom: 20px;
        
        .el-form-item__label {
          font-weight: 500;
          color: #303133;
        }
        
        .el-input, .el-select, .el-textarea {
          .el-input__inner, .el-select__wrapper, .el-textarea__inner {
            border-radius: 6px;
            border: 1px solid #dcdfe6;
            transition: all 0.2s;
            
            &:focus {
              border-color: #409eff;
              box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
            }
          }
        }
        
        .el-switch {
          .el-switch__core {
            border-radius: 12px;
          }
        }
      }
      
      .el-textarea {
        .el-textarea__inner {
          min-height: 100px;
          resize: vertical;
        }
      }
      
      .el-form-item:last-child {
        margin-bottom: 0;
        padding-top: 16px;
        border-top: 1px solid #f0f0f0;
        
        .el-button {
          padding: 10px 24px;
          border-radius: 6px;
          font-weight: 500;
          
          &.el-button--primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
            
            &:hover {
              transform: translateY(-1px);
              box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
            }
          }
        }
      }
    }
  }
}

/* 详情面板样式优化 */
.interface-detail, .scenario-detail, .execution-detail, .environment-detail {
  height: 100%;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  
  .detail-header {
    padding: 20px 24px 16px 24px;
    border-bottom: 1px solid #e4e7ed;
    background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .interface-title, .scenario-title, .execution-title, .environment-title {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .name {
        font-weight: 600;
        font-size: 18px;
        color: white;
      }
      
      .el-tag {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        color: white;
        font-weight: 500;
      }
      
      .environment-tags {
        display: flex;
        gap: 8px;
        
        .el-tag {
          background: rgba(255, 255, 255, 0.2);
          border: 1px solid rgba(255, 255, 255, 0.3);
          color: white;
          font-weight: 500;
        }
      }
    }
    
    .actions {
      display: flex;
      gap: 8px;
      
      .el-button {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        color: white;
        font-weight: 500;
        
        &:hover {
          background: rgba(255, 255, 255, 0.3);
          border-color: rgba(255, 255, 255, 0.5);
          transform: translateY(-1px);
        }
        
        &.el-button--danger {
          background: rgba(244, 67, 54, 0.8);
          border-color: rgba(244, 67, 54, 0.8);
          
          &:hover {
            background: rgba(244, 67, 54, 0.9);
            border-color: rgba(244, 67, 54, 0.9);
          }
        }
      }
    }
  }
  
  .detail-content {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
    background: #fafbfc;
    
    .detail-section {
      background: white;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
  padding: 20px;
      margin-bottom: 16px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
      
      &:last-child {
        margin-bottom: 0;
      }
      
      h4 {
        margin: 0 0 16px 0;
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        display: flex;
        align-items: center;
        gap: 8px;
        
        &::before {
          content: "📋";
          font-size: 14px;
        }
      }
      
      .info-grid {
        .info-item {
          display: flex;
          margin-bottom: 12px;
          padding: 8px 0;
          border-bottom: 1px solid #f5f5f5;
          font-size: 14px;
          
          &:last-child {
            border-bottom: none;
            margin-bottom: 0;
          }
          
          label {
            width: 100px;
            color: #666;
            font-weight: 500;
            flex-shrink: 0;
          }
          
          span {
            flex: 1;
            color: #303133;
            word-break: break-all;
          }
        }
      }
      
      .param-list, .assertion-list, .headers-list, .variables-list, .steps-list {
        .param-item, .assertion-item, .header-item, .variable-item, .step-item {
          padding: 12px;
          border: 1px solid #e4e7ed;
          border-radius: 6px;
          margin-bottom: 8px;
          background: #fafbfc;
          transition: all 0.2s;
          
          &:hover {
            border-color: #409eff;
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
          }
          
          &:last-child {
            margin-bottom: 0;
          }
        }
      }
      
      .result-summary {
        display: flex;
        gap: 16px;
        
        .result-item {
          flex: 1;
          padding: 16px;
          border-radius: 8px;
          text-align: center;
          border: 2px solid;
          transition: all 0.2s;
          
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          }
          
          .label {
            display: block;
            font-size: 14px;
            margin-bottom: 8px;
            font-weight: 500;
          }
          
          .count {
            display: block;
            font-size: 24px;
            font-weight: bold;
          }
        }
      }
      
      .status-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
        
        .status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
          padding: 12px;
          border: 1px solid #e4e7ed;
          border-radius: 6px;
          background: #fafbfc;
          font-size: 14px;
          transition: all 0.2s;
          
          &:hover {
            border-color: #409eff;
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
          }
          
          label {
            color: #666;
            font-weight: 500;
          }
          
          .status-yes {
            color: #67C23A;
  font-weight: 600;
}

          .status-no {
            color: #999;
          }
        }
      }
      
      .error-message {
        padding: 16px;
        background: #fef0f0;
        border: 1px solid #F56C6C;
        border-radius: 6px;
        color: #F56C6C;
        font-size: 13px;
        font-family: 'Monaco', 'Menlo', monospace;
        white-space: pre-wrap;
        line-height: 1.5;
      }
    }
  }
}

/* 参数配置样式 */
.param-section {
  .param-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    font-weight: 500;
    color: #303133;
  }
  
  .empty-params {
  text-align: center;
    color: #909399;
    font-size: 13px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;
  }
  
  .param-list {
    .param-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      padding: 12px;
      background: #f8f9fa;
      border-radius: 6px;
      border: 1px solid #e4e7ed;
      min-width: 600px; /* 增加最小宽度 */
      
      &:last-child {
        margin-bottom: 0;
      }
      
      /* 优化输入框布局 */
      .el-input {
        flex: 1;
        margin-right: 8px;
        
        &:last-of-type {
          margin-right: 0;
        }
      }
      
      .el-button {
        margin-left: 8px;
        flex-shrink: 0;
      }
    }
  }
  
  .json-editor, .raw-editor {
    min-width: 600px; /* JSON和Raw编辑器也增加宽度 */
    
    .el-textarea {
      .el-textarea__inner {
        font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
        font-size: 13px;
        line-height: 1.4;
        min-height: 120px; /* 增加高度 */
      }
    }
  }
}

/* 创建表单内容区域优化 */
.create-form {
  .form-content {
    .el-form {
      max-width: none; /* 移除最大宽度限制 */
      width: 100%;
      
      .el-form-item {
        &:has(.el-tabs) {
          .el-form-item__content {
            width: 100%;
            
            .el-tabs {
              width: 100%;
              
              .el-tab-pane {
                width: 100%;
              }
            }
          }
        }
      }
    }
  }
}

/* 抽屉内容样式 */
.drawer-content {
  padding: 20px;
  
  .steps-section {
    .steps-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 1px solid #e4e7ed;
    }
    
    .empty-steps {
      text-align: center;
      padding: 40px 20px;
    }
    
    .steps-list {
      .step-item {
        border: 1px solid #e4e7ed;
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 12px;
        background: white;
        transition: all 0.2s;
        
        &:hover {
          border-color: #409eff;
          box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
        }
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .step-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
          
          .step-number {
            font-weight: 600;
            color: #409eff;
          }
          
          .step-actions {
            display: flex;
            gap: 8px;
          }
        }
        
        .step-interface {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;
          
          .interface-name {
            font-weight: 500;
    color: #303133;
  }
  
          .interface-url {
            color: #909399;
            font-size: 13px;
          }
        }
        
        .step-params {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          gap: 4px;
          
          .params-label {
            font-size: 13px;
    color: #666;
            margin-right: 4px;
          }
        }
      }
    }
  }
}

/* 统一接口管理布局 */
.unified-interface-layout {
  display: flex;
  height: calc(100vh - 200px); // 使用固定计算高度
  min-height: 500px; // 确保最小高度
  
  .interface-sidebar {
    width: 400px;
    border-right: 1px solid #e4e7ed;
    display: flex;
    flex-direction: column;
    
    .sidebar-header {
      padding: 12px 16px;
      border-bottom: 1px solid #e4e7ed;
      background: #fafbfc;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .search-filters {
        display: flex;
        align-items: center;
        gap: 8px;
        flex: 1;
      }
      
      .header-actions {
        display: flex;
        margin-left: 8px;
      }
    }
    
    .interface-list {
      flex: 1;
      overflow-y: auto;
      padding: 8px;
    }
    
    .pagination-small {
      padding: 8px 16px;
      border-top: 1px solid #e4e7ed;
    }
  }
  
  .interface-editor {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
}
</style>